#include "cmyudp.h"

CMyUdp::CMyUdp()
{
    m_flagConnected = false;
    udpSocket = new QUdpSocket();
}
CMyUdp::~CMyUdp()
{
    if (udpSocket != NULL)
    {
        delete udpSocket;
        udpSocket = NULL;
    }
}
void CMyUdp::SetParam(UdpSetStruct setInfo)
{
    mSet = setInfo;
}

bool CMyUdp::OpenUdp()
{
    bool result;

    QHostAddress addr;
    if (mSet.localPort <= 0)
    {
        mSet.localPort = DEFAULTPORT;
    }

    if (mSet.localIP.isEmpty())
    {
        result = udpSocket->bind(QHostAddress::LocalHost,mSet.localPort);
    }
    else
    {
        addr = QHostAddress(mSet.localIP);
        result = udpSocket->bind(addr,mSet.localPort);
    }
//    qDebug()<<"result:"<<result;
    if (result)
    {
        connect(udpSocket,SIGNAL(readyRead()),this,SLOT(readPendingDatagrams()));

    }
    m_flagConnected = result;
    return m_flagConnected;
}

void CMyUdp::CloseUdp()
{
    m_flagConnected = false;
    udpSocket->close();
}
bool CMyUdp::IsConnected()
{
    return m_flagConnected;
}

UdpSetStruct CMyUdp::GetUdpSet()
{
    return mSet;
}

void CMyUdp::readPendingDatagrams()
 {
     while (udpSocket->hasPendingDatagrams()) {
         QByteArray datagram;
         datagram.resize(udpSocket->pendingDatagramSize());
         QHostAddress sender;
         quint16 senderPort;

         udpSocket->readDatagram(datagram.data(), datagram.size(),
                                 &sender, &senderPort);

         emit UdpRecv (datagram.data(),datagram.size());
     }
 }

int CMyUdp::SendData(const char *data, int size, QString address, quint16 port )
{
    QHostAddress addr(address);
    return udpSocket->writeDatagram(data,size,addr,port);
}

